# PowerShell initialization script
$ErrorActionPreference = "Stop"

Write-Host "Waiting for PostgreSQL to start..."
$connected = $false
$maxAttempts = 30
$attempt = 0

while (-not $connected -and $attempt -lt $maxAttempts) {
    $attempt++
    try {
        $env:PGPASSWORD = $env:POSTGRES_PASSWORD
        & psql -h $env:POSTGRES_HOST -p $env:POSTGRES_PORT -U $env:POSTGRES_USER -d $env:POSTGRES_DB -c "\q"
        $connected = $true
        Write-Host "PostgreSQL is up and running!"
    } catch {
        Write-Host "PostgreSQL is unavailable - sleeping ($attempt/$maxAttempts)"
        Start-Sleep -s 1
    }
}

if (-not $connected) {
    Write-Host "Failed to connect to PostgreSQL after $maxAttempts attempts."
    exit 1
}

Write-Host "Executing migrations..."
Set-Location /app
& alembic revision --autogenerate -m "Initial migration"
& alembic upgrade head

Write-Host "Migrations complete, starting application"
# Execute the command passed to this script
& $args[0] $args[1..($args.Length-1)]